package com.xiaoming.e3mall.sso.service.impl;

import com.xiaoming.e3mall.common.jedis.JedisClient;
import com.xiaoming.e3mall.common.utils.E3Result;
import com.xiaoming.e3mall.common.utils.JsonUtils;
import com.xiaoming.e3mall.mapper.TbUserMapper;
import com.xiaoming.e3mall.pojo.TbUser;
import com.xiaoming.e3mall.pojo.TbUserExample;
import com.xiaoming.e3mall.sso.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private JedisClient jedisClient;


    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public E3Result userLogin(String username, String password) {

        // 1、判断用户和密码是否正确
        //根据用户名查询用户信息
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        //执行查询
        List<TbUser> list = userMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            //返回登录失败
            return E3Result.build(400, "用户名或密码错误");
        }
        //取用户信息
        TbUser user = list.get(0);
        //判断密码是否正确
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            // 2、如果不正确，返回登录失败
            return E3Result.build(400, "用户名或密码错误");
        }

        //3.如果用户名跟密码正确登录成功
            //生成token(相当于JsessionId)
        String token = UUID.randomUUID().toString();
        //4.使用Redis存储用户信息(这里把redis想象成一个HttpServlet)
            //key就是token,value就是tbuser对象转成的json串
        user.setPassword(null);
        jedisClient.set("SESSION:" + token, JsonUtils.objectToJson(user));
        //5.设置过期时间默认为30分钟
        jedisClient.expire("SESSION:"+token, SESSION_EXPIRE);
        //6.把token返回
            //还要把token写入到cookie中,但是我们现在是在service层没法写只能到Controller层中写
        return E3Result.ok(token);
    }
}
